package com.itheima.stock.service.impl;

import com.itheima.stock.cache.Cache;
import com.itheima.stock.constant.Constants;
import com.itheima.stock.service.UserService;
import com.itheima.stock.util.IdWorkers;
import com.itheima.stock.util.RedisKeyUtil;
import com.itheima.stock.vo.CaptchaVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户接口实现
 */
@Service
public class UserServiceImpl implements UserService {
    private final IdWorkers idWorkers;

    private final Cache cache;

    /**
     * 定义随机数的位数
     */
    private static final int FOUR = 4;

    public UserServiceImpl(Cache cache, IdWorkers idWorkers) {
        this.cache = cache;
        this.idWorkers = idWorkers;
    }

    @Override
    public CaptchaVO captcha() {
        //1 生成随机4位验证码
         String captcha = RandomStringUtils.randomNumeric(FOUR);
        //2将验证码存储到redis(key、架构设计）
        //2.1生成redis的key
        String redisKey = RedisKeyUtil.generateKey(Constants.CAPTCHA_PREFIX, idWorkers.nextStrId());
        //2.2调用缓存接口存入验证码
        cache.set(redisKey, captcha, Constants.CAPTCHA_EXPIRE_TIME);
        //3数据组装返回
        return CaptchaVO.builder()
                .rkey(redisKey)
                .code(captcha)
                .build();
    }
}
